package jobase

import (
	"encoding/json"
	"gitee.com/jolib/jokode"
	"github.com/pkg/errors"
	"os"
)

func Json2Str(obj any) string {
	if data, err := json.Marshal(obj); err != nil {
		jokode.Errorf("try marshal obj fail, error info: %v", err)
		return ""
	} else {
		return string(data)
	}
}

func Str2Json(data string, obj any) (ok bool) {
	if err := json.Unmarshal([]byte(data), obj); err != nil {
		jokode.Errorf("try unmarshal obj fail, error info: %v", err)
		return false
	} else {
		return true
	}
}

func LoadJsonObjectFromFile(obj any, filePath string) error {
	if data, err := os.ReadFile(filePath); err != nil {
		return errors.Wrapf(err, "try read file '%s' fail when try load json object", filePath)
	} else if len(data) == 0 {
		return errors.Errorf("try read file '%s' returns emtpy when try laod json object", filePath)
	} else {
		if err = json.Unmarshal(data, obj); err != nil {
			return errors.Wrapf(err, "try unmarshal json object fail, when read it from file '%s'", filePath)
		} else {
			return nil
		}
	}
}

func SaveJsonObjectToFile(obj any, filePath string) error {
	if data, err := json.MarshalIndent(obj, "", "  "); err != nil {
		return errors.Wrapf(err, "try marshal obj fail when try save object to file '%s'", filePath)
	} else {
		if err = os.WriteFile(filePath, data, 0644); err != nil {
			return errors.Wrapf(err, "try write file '%s' fail when try save object to file '%s'", filePath, filePath)
		} else {
			return nil
		}
	}
}
